<?php

namespace Modules\Backend\Auth;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Modules\Backend\Http\Requests\AdminLoginRequest;


trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;

    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:26
     * @Description:登录表单
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function showLoginForm()
    {
        $bg_files=Storage::disk("assets")->files("backend/images/bg");
        $count=count($bg_files);
        $index=random_int(0,$count-1);
        $wallpaper='/assets/'.$bg_files[$index];

        $ip=ip2long(request()->getClientIp());
        $cookie_name = sha1('ip.' . $ip);
        $cookie = unserialize(Cookie::get($cookie_name));
        $admin = [];
        if (!isset($cookie['ip']) || $cookie['ip'] != $ip) {
            //清除cookie
            Cookie::queue(Cookie::forget($cookie_name));
        } else {
            $admin['avatar'] =isset($cookie['avatar'])?$cookie['avatar']:"";
            $admin['user_name']=$admin['nick_name']= isset($cookie['user_name'])?$cookie['user_name']:"";
            if(isset($cookie['nick_name']) && $cookie['nick_name']){
                $admin['nick_name'] =$cookie['nick_name'];
            }


        }

        return view('backend::auth.login',compact("wallpaper","admin"));
    }

    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:26
     * @Description:登录提交
     * @param AdminLoginRequest $request
     * @return \Illuminate\Http\RedirectResponse|void
     */
    public function login(AdminLoginRequest $request)
    {
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }


    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:27
     * @Description: 登录，用户名或邮箱校验
     * @param Request $request
     * @return mixed
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        )||$this->guard()->attempt(
            $this->credentialsEmail($request), $request->filled('remember')
        );
    }

    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:27
     * @Description:验证的字段
     * @param Request $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    protected function credentialsEmail(Request $request)
    {
        return ["email"=>e($request->get("user_name")),"password"=>e($request->get("password"))];
    }

    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:27
     * @Description:
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:27
     * @Description:登录成功
     * @param Request $request
     * @param $user
     * @return \Illuminate\Http\JsonResponse
     */
    protected function authenticated(Request $request, $user)
    {
        $ip=$request->getClientIp();
        $user->login_ip=$ip;
        $user->login_count=$user->login_count+1;
        $user->save();

        $data['user_name'] = $user->user_name;
        $data['nick_name'] = $user->nick_name;
        $data['avatar'] = $user->avatar;
        $data['ip'] = ip2long($ip);

        $cookie_name = sha1('ip.' . ip2long($ip));
        $cookie_value = serialize($data);
        Cookie::queue($cookie_name, $cookie_value, 604800);
        return responseJsonData("登录成功",1,route("backend.index.index"));
    }


    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:27
     * @Description:验证失败抛出信息
     * @param Request $request
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'user_name';
    }

    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:28
     * @Description:退出
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();
        $request->session()->invalidate();
        return $this->loggedOut($request) ?: redirect(route("backend.login"));
    }

    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:19
     * @Description: 退出执行操作
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    protected function loggedOut(Request $request)
    {
        return responseJsonData("成功退出",1,route("backend.login"));
//        return  redirect(route("backend.login"));
    }

    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/3 16:19
     * @Description:设置 guard
     * @return mixed
     */
    protected function guard()
    {
        return Auth::guard("backend");
    }
}
